package avicit.bdp.dms.tdm.event;

import avicit.bdp.core.util.json.JSONUtils;
import avicit.bdp.dms.tdm.dto.AssetApplyDTO;
import avicit.bdp.dms.tdm.dto.BdpAssetDTO;
import avicit.bdp.dms.tdm.dto.ProcessApproveDTO;
import avicit.bdp.dms.tdm.service.AssetApplyService;
import avicit.bdp.dms.tdm.service.BdpAssetService;
import avicit.bdp.dms.tdm.service.ProcessApproveService;
import avicit.bdp.dms.tdm.utils.CheckerStatus;
import avicit.bdp.dms.tdm.utils.FlowType;
import avicit.bdp.dms.tdm.utils.ReleaseStatus;
import avicit.platform6.api.bpm.eventInterface.CommonRestEventInterface;
import avicit.platform6.api.system.SysUserClient;
import avicit.platform6.core.exception.BusinessException;
import avicit.platform6.core.rest.msg.ResponseMsg;
import avicit.platform6.core.spring.SpringFactory;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @金航数码科技有限责任公司
 * @作者：${tableInfo.classCreator}
 * @邮箱：${tableInfo.classMailbox}
 * @创建时间： 2023-11-22 16:56
 * @类说明：我的审核结束事件
 * @修改记录：
 */
@RestController
@RequestMapping("/api/bdp/dms/process/approve/ProcessApproveEndEvent")
public class ProcessApproveEndEvent implements CommonRestEventInterface {

    private static final Logger logger = LoggerFactory.getLogger(ProcessApproveEndEvent.class);

    /**
     * 流程表
     */
    ProcessApproveService processApproveService = SpringFactory.getBean(ProcessApproveService.class);
    /**
     * 资产表
     */
    BdpAssetService bdpAssetService = SpringFactory.getBean(BdpAssetService.class);
    /**
     * 申请表
     */
    AssetApplyService assetApplyService = SpringFactory.getBean(AssetApplyService.class);
    /**
     * 一级单位表
     */
    SysUserClient sysUserClient = SpringFactory.getBean(SysUserClient.class);

    @Override
    @PostMapping("/notify_end/v1")
    public ResponseMsg<Void> notify(@RequestBody Map<String, String> args) {
        ResponseMsg<Void> responseMsg = new ResponseMsg<>();
        String formId = args.get("formId");
        if (StringUtils.isEmpty(formId)) {
            throw new BusinessException("formId为空");
        }
        ProcessApproveDTO processApprove = processApproveService.selectByPrimaryKey(formId);
        if (processApprove == null) {
            throw new BusinessException("流程数据为空");
        }
        //更新数据
        this.updateDataSensitive(processApprove);
        return responseMsg;
    }

    /**
     * 处理流程回到第一个节点时触发的事件
     *
     * @param args
     * @return avicit.platform6.core.rest.msg.ResponseMsg<java.lang.Void>
     * @date 2024/3/29 16:49
     */
    @PostMapping("/notify_first_task/v1")
    public ResponseMsg<Void> notifyFirstTask(@RequestBody Map<String, String> args) {
        ResponseMsg<Void> responseMsg = new ResponseMsg<>();
        String formId = args.get("formId");
        if (StringUtils.isEmpty(formId)) {
            throw new BusinessException("formId为空");
        }
        ProcessApproveDTO processApprove = processApproveService.selectByPrimaryKey(formId);
        //如果申请记录为空，表示刚启动流程
        if (processApprove == null) {
            return responseMsg;
        }
        String opType = args.get("opType");
        if(StringUtils.isNotBlank(opType)){
            opType = opType.replaceAll("\"","");
        }
        logger.info("流程事件：" + processApprove.getBusinessTitle() + "------" + opType + "----" + JSONUtils.toJson(args));
        //退到拟稿人节点时，按审批拒绝处理 更新数据
        int flowType = processApprove.getFlowType();
        if (flowType == FlowType.PUBLISH.getCode() || flowType == FlowType.REVOKE.getCode()) {
            //更新资产发布审核状态
            this.updateAssetNotApproved(processApprove, opType);
        } else if (flowType == FlowType.APPLY.getCode()) {
            //更新资产申请审核状态
            this.updateApplyNotApproved(processApprove, opType);
        }
        return responseMsg;
    }

    /**
     * 更新申请表审批状态
     */
    private void updateApplyNotApproved(ProcessApproveDTO processApprove, String opType) {
        AssetApplyDTO applyDTO = assetApplyService.selectByPrimaryKey(processApprove.getBusinessId());
        if (applyDTO == null) {
            return;
        }
        if (isWithdraw(opType)) {
            //流程拿回
            applyDTO.setCheckerStatus(CheckerStatus.REVOKE_APPROVED.getCode());
        } else if (isDoRetreat(opType)) {
            //流程退回
            applyDTO.setCheckerStatus(CheckerStatus.NOT_APPROVED.getCode());
        }

        assetApplyService.updateByPrimaryKeySelective(applyDTO);
    }

    /**
     * 判断是否是流程拿回
     *
     * @param opType
     * @return boolean
     * @date 2024/3/29 17:03
     */
    private boolean isWithdraw(String opType) {
        return StringUtils.isNotBlank(opType) && opType.startsWith("dowithdraw");
    }

    private boolean isDoRetreat(String opType) {
        return StringUtils.isNotBlank(opType) && opType.startsWith("doretreat");
    }

    private boolean isDoSubmit(String opType) {
        return StringUtils.isNotBlank(opType) && opType.startsWith("dosubmit");
    }

    /**
     * 更新资产表审批状态
     */
    private void updateAssetNotApproved(ProcessApproveDTO processApprove, String opType) {
        BdpAssetDTO assetDTO = bdpAssetService.selectByPrimaryKey(processApprove.getBusinessId());
        if (assetDTO == null) {
            return;
        }

        //发布状态设置为已发布;
        assetDTO.setReleaseDate(null);
        if (isWithdraw(opType)) {
            //流程拿回
            if (ReleaseStatus.PUBLISHED.getCode() == assetDTO.getReleaseStatus()) {
                //资产撤回申请时，如果自己流程拿回，则把审批状态恢复到审批已通过
                assetDTO.setCheckerStatus(CheckerStatus.APPROVED.getCode());
            } else {
                assetDTO.setCheckerStatus(CheckerStatus.REVOKE_APPROVED.getCode());
            }

        } else if (isDoRetreat(opType)) {
            //流程退回
            assetDTO.setCheckerStatus(CheckerStatus.NOT_APPROVED.getCode());
        } else if (isDoSubmit(opType)) {
            //流程提交
            if (FlowType.PUBLISH.getCode() == processApprove.getFlowType()) {
                assetDTO.setCheckerStatus(CheckerStatus.WAIT_PUBLISH_APPROVE.getCode());
            } else {
                assetDTO.setCheckerStatus(CheckerStatus.WAIT_REVOKE_APPROVE.getCode());
            }

        }
        bdpAssetService.updateByPrimaryKey(assetDTO);
    }


    private void updateDataSensitive(ProcessApproveDTO processApprove) {
        int flowType = processApprove.getFlowType();
        if (flowType == FlowType.PUBLISH.getCode()) {
            //审核通过后，更新发布人发布时间发布状态
            this.updateAssetSensitive(processApprove);
        } else if (flowType == FlowType.REVOKE.getCode()) {
            //审核通过后，更新资产发布状态
            this.updateAssetRevoke(processApprove);
        } else if (flowType == FlowType.APPLY.getCode()) {
            //更新审核状态
            this.updateApplySensitive(processApprove);
        }
    }

    /**
     * 更新资产表数据
     */
    private void updateAssetSensitive(ProcessApproveDTO processApprove) {
        BdpAssetDTO assetDTO = bdpAssetService.selectByPrimaryKey(processApprove.getBusinessId());
        if (assetDTO == null) {
            return;
        }
        assetDTO.setReleaser(assetDTO.getCreatedBy());
//        assetDTO.setReleaseDate(new Date());
//        SysUser sysUser = sysUserClient.getSysUserById(assetDTO.getCreatedBy());
//        logger.info("sysUser = {}", sysUser);
//        if (sysUser != null) {
//            assetDTO.setReleaseDept(sysUser.getDeptId());
//        }

        //发布状态设置为已发布
        assetDTO.setReleaseStatus(ReleaseStatus.PUBLISHED.getCode());
        assetDTO.setCheckerStatus(CheckerStatus.APPROVED.getCode());
        bdpAssetService.updateByPrimaryKeySelective(assetDTO);
    }

    /**
     * 更新资产表数据
     */
    private void updateAssetRevoke(ProcessApproveDTO processApprove) {
        BdpAssetDTO assetDTO = bdpAssetService.selectByPrimaryKey(processApprove.getBusinessId());
        if (assetDTO == null) {
            return;
        }

        //发布状态设置为已撤回
        assetDTO.setReleaseStatus(ReleaseStatus.REVOKED.getCode());
        assetDTO.setCheckerStatus(CheckerStatus.APPROVED.getCode());
        bdpAssetService.updateByPrimaryKeySelective(assetDTO);
    }

    /**
     * 更新申请表数据
     */
    private void updateApplySensitive(ProcessApproveDTO processApprove) {
        AssetApplyDTO applyDTO = assetApplyService.selectByPrimaryKey(processApprove.getBusinessId());
        if (applyDTO == null) {
            return;
        }
        applyDTO.setCheckerStatus(CheckerStatus.APPROVED.getCode());
        assetApplyService.updateByPrimaryKeySelective(applyDTO);
    }

}